<!DOCTYPE html>
<html lang="en">
<head>
    <th:block th:include="include :: header('未排课记上课')"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: timepicker-css"/>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form class="form-horizontal m" id="form-schedule-info">
                <input name="classId" th:field="*{teachingClasses.classId}" type="hidden">
                <input name="courseId" th:field="*{teachingClasses.courseId}" type="hidden">
                <input name="status" value="1" type="hidden">
                <div class="form-group">
                    <div class="col-sm-4">
                        <label class="col-sm-4 control-label">上课日期：</label>
                        <div class="col-sm-6">
                            <div class="input-group date">
                                <input name="startDate" th:value="${#dates.format(new java.util.Date(), 'yyyy-MM-dd')}"
                                       class="form-control" placeholder="请选择日期" type="text">
                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-4">
                        <label class="col-sm-4 control-label">上课时间段：</label>
                        <div class="col-sm-2">
                            <div class="input-group date">
                                <input name="startTime" class="form-control" placeholder="HH-mm" type="text" required readonly>
                            </div>
                        </div>
                        <div class="col-sm-2">
                            <div class="input-group date">
                                <input name="endTime" class="form-control" placeholder="HH-mm" type="text" required readonly>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-4">
                        <label class="col-sm-4 control-label">上课老师：</label>
                        <div class="col-sm-6">
                            <select class="form-control" id="teacherId" name="teacherId">
                                <option th:each="teacher:${teachers}"
                                        th:value="${teacher.userId}"
                                        th:text="${teacher.userName}">
                                </option>
                            </select>
                        </div>
                    </div>
                    <div class="col-sm-4">
                        <label class="col-sm-4 control-label">老师课时：</label>
                        <div class="col-sm-3" style="width: 78px">
                            <input class="form-control" type="number" th:field="*{teachingClasses.teacherIncrease}">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-4">
                        <label class="col-sm-4 control-label">备注：</label>
                        <div class="col-sm-8">
                            <div class="form-control">[[*{teachingClasses.remark}]]</div>
                        </div>
                    </div>
                </div>
            </form>
            <div class="tabs-container" style="padding-top: 20px;">
                <ul class="nav nav-tabs">
                    <li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true">学生记上课</a>
                    </li>
                </ul>
                <div class="btn-group-sm" id="toolbar" role="group">
                    <a class="btn btn-success" onclick="addTemporaryStudent()">
                        <i class="fa fa-plus"></i> 添加临时学员
                    </a>
                </div>
                <div class="tab-content">
                    <div id="tab-1" class="tab-pane active">
                        <div class="panel-body">
                            <table id="bootstrap-table"></table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-offset-5 col-sm-10">
                <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i
                        class="fa fa-check"></i>保 存
                </button>&nbsp;
                <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i
                        class="fa fa-reply-all"></i>关 闭
                </button>
            </div>
        </div>
    </div>
</div>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:include="include :: timepicker-js"/>
<script th:src="@{/js/jquery.tmpl.js}"></script>
<script th:inline="javascript">
    var classId = [[${teachingClasses.classId}]];
    var className = [[${teachingClasses.className}]];
    var courseId = [[${teachingClasses.courseId}]];
    var schoolId = [[${teachingClasses.schoolId}]];
    var teacherIncrease = [[${teachingClasses.teacherIncrease}]];
    var classStudent = [[${teachingClasses.classStudent}]];
    var studentConsume = [[${teachingClasses.studentConsume}]];
    var data1 = [[${@dict.getType('sys_record_status')}]];

    $(function () {
        var options = {
            url: ctx + "teaching/students/list",
            queryParams: {classId: classId},
            modalName: "记上课学员",
            showSearch: false,
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            pagination: false,
            columns: [{
                checkbox: false,
                visible: false
            },
                {
                    field: 'teachingStudentApply.applyId',
                    title: '主键ID',
                    visible: false
                },
                {
                    field: 'classStudentId',
                    title: '班级学生ID',
                    visible: false
                },
                {
                    field: 'classId',
                    title: '班级ID',
                    visible: false
                },
                {
                    field: 'teachingClasses.className',
                    title: '班级名称',
                    visible: false
                },
                {
                    field: 'schoolId',
                    title: '学校ID',
                    visible: false
                },
                {
                    field: 'teachingStudent.studentName',
                    title: '学生姓名',
                },
                {
                    field: 'teachingStudentApply.lessonRemain',
                    title: '剩余课时',
                },
                {
                    field: 'leaveCount',
                    title: '请假次数',
                },
                {
                    field: 'teachingClasses.studentConsume',
                    title: '本次扣课时',
                    formatter: function (value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' style='width: 50px' type='number' name='lessonConsume' id='lessonConsume' value='%s'>", value);
                        html += $.common.sprintf("<input type='hidden' name='applyId' value='%s'>", row.teachingStudentApply.applyId);
                        html += $.common.sprintf("<input type='hidden' name='schoolId' value='%s'>", row.schoolId);
                        html += $.common.sprintf("<input type='hidden' name='classStudentId' value='%s'>", row.classStudentId);
                        html += $.common.sprintf("<input type='hidden' name='studentName' value='%s'>", row.teachingStudent.studentName);
                        html += $.common.sprintf("<input type='hidden' name='lessonRemain' value='%s'>", row.teachingStudentApply.lessonRemain);
                        html += $.common.sprintf("<input type='hidden' name='leaveCount' value='%s'>", row.leaveCount);
                        html += $.common.sprintf("<input type='hidden' name='lessonConsume1' value='%s'>", value);
                        return html;
                    }
                },
                {
                    field: 'attendStatus',
                    title: '到课状态',
                    formatter: function (value, row, index) {
                        var data = [{index: index, type: 0}];
                        return $("#attendStatus").tmpl(data).html();
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="remove(this)"><i class="fa fa-remove"></i>移除</a>');
                        return actions.join('');
                    }
                }
            ],
        };
        $.table.init(options);
    });

    function submitHandler() {
        var rows = $("#bootstrap-table tbody tr");
        if (rows.length == 0) {
            $.modal.alertError("请至少选择一条记录");
            return;
        } else {
            addClassRecord();
        }
    }

    /* 临时移除学员 */
    function remove(obj) {
        var tr = $(obj).parent().parent();
        $.modal.confirm("确定删除该条" + table.options.modalName + "信息吗？", function () {
            $(tr).remove();
        });
    }

    /* 添加临时学生 */
    function addTemporaryStudent() {
        // var url = ctx + "teaching/record"
        // $.modal.open("添加临时上课学生", url + "/temporaryStudent/" + classId);
        var url = ctx + "teaching/record/temporaryStudent/" + classId;
        var options = {
            title: '选择学生',
            url: url,
            callBack: doSubmit
        };
        $.modal.openOptions(options);
    }


    function doSubmit(index, layero) {
        var applyIds = layero.find("iframe")[0].contentWindow.getSelections("applyId");
        if (applyIds.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        var studentNames = layero.find("iframe")[0].contentWindow.getSelections("studentName");
        var lessonRemain = layero.find("iframe")[0].contentWindow.getSelections("lessonRemain");
        var currentIndex = ($("#bootstrap-table select").length - 1);
        $.each(applyIds, function (index, value) {
            currentIndex += 1;
            var tr = $("<tr></tr>>");
            tr.append($("<td></td>>").text(studentNames[index]));
            tr.append($("<td></td>>").text(lessonRemain[index]));
            tr.append($("<td></td>>").text("0"));
            var td = $("<td></td>");
            td.append($("<input type='number' style='width:50px' class='form-control' name='lessonConsume'/>").val(studentConsume));
            td.append($.common.sprintf("<input type='hidden' name='applyId' value='%s'>", applyIds[index]));
            td.append($.common.sprintf("<input type='hidden' name='schoolId' value='%s'>", schoolId));
            td.append($.common.sprintf("<input type='hidden' name='classStudentId' value='%s'>", 0))
            td.append($.common.sprintf("<input type='hidden' name='studentName' value='%s'>", studentNames[index]));
            td.append($.common.sprintf("<input type='hidden' name='lessonRemain' value='%s'>", lessonRemain[index]));
            td.append($.common.sprintf("<input type='hidden' name='leaveCount' value='%s'>", 0));
            td.append($.common.sprintf("<input type='hidden' name='lessonConsume1' value='%s'>", studentConsume))
            tr.append(td);

            var data = [{index: currentIndex, type: 0}];
            var select = $("#attendStatus").tmpl(data).html();
            tr.append($("<td></td>>").append(select));
            tr.append($("<td style='text-align: center'></td>>").append('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="remove(this)"><i class="fa fa-remove"></i>移除</a>'));

            $("#bootstrap-table tbody").append(tr);
        });
        $.modal.close(index);
    }

    /* 新增班级上课记录 */
    function addClassRecord() {
        var trs = $("#bootstrap-table tbody tr");
        // console.log(trs.length);
        var startDate = $("input[name='startDate']").val();
        var startTime = $("input[name='startTime']").val();
        var endTime = $("input[name='endTime']").val();
        var teacherId = $("#teacherId option:selected").val();
        var teacherName = $("#teacherId option:selected").text();
        var studentHour = 0;
        var attendance = 0;
        var leaveCount = 0;
        var truantCount = 0;
        var flag = 0;
        var count = 0;
        var studentNames = "";
        $.each(trs, function (index, value) {
            // console.log(index);
            let lessonConsume = $(value).find("input[name=lessonConsume]").val();
            let attendStatus = $(value).find("select").val();
            // console.log("select[name='attendStatus[" + index + "].type']");
            // console.log(attendStatus);
            let lessonRemain = $(value).find("input[name=lessonRemain]").val();
            let studentName = $(value).find("input[name=studentName]").val();
            if (parseInt(lessonRemain) < parseInt(lessonConsume)) {
                count++;
                studentNames += studentName + "同学,";
                // $.modal.msgError(studentName + "同学剩余课时不足, 请调整扣除课时或完成续费");
                // return false;
            }
            studentHour += parseInt(lessonConsume);
            if (attendStatus == 0) {
                attendance++;
            } else if (attendStatus == 1) {
                leaveCount++;
            } else if (attendStatus == 2) {
                truantCount++;
            }
        });
        // return false;
        // var rows = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
        // if (rows.length == 0) {
        //     $.modal.alertWarning("请至少选择一条记录");
        //     return;
        // } else {
        if (count > 0) {
            top.layer.msg(studentNames + "剩余课时不足, 请调整扣除课时或完成续费", {
                icon: $.modal.icon(modal_status.FAIL),
                time: 3000,
                shift: 5
            });
            // $.modal.msgError(studentNames + "同学剩余课时不足, 请调整扣除课时或完成续费");
            return false;
        }
        $.ajax({
            type: "post",
            url: ctx + "teaching/classRecord/add",
            async: false,
            data: {
                "classId": classId,
                "schoolId": schoolId,
                "startDate": startDate,
                "className": className,
                "courseId": courseId,
                "teacherId": teacherId,
                "teacherName": teacherName,
                "startTime": startTime,
                "endTime": endTime,
                "attendance": attendance,
                "peopleCount": classStudent,
                "leaveCount": leaveCount,
                "truantCount": truantCount,
                "studentHour": studentHour,
                "teacherHour": teacherIncrease,
            },
            success: function (result) {
                if (result.code == 0) {
                    let clsRecordId = result.data.claRecordId;
                    studentRecord(clsRecordId);
                    $.operate.successTabCallback(result);

                }
            }
        });

    }

    /* 新增学生上课记录 */
    function studentRecord(clsRecordId) {
        var trs = $("#bootstrap-table tbody tr");
        var records = [];
        $.each(trs, function (index, value) {
            let record = {};
            record.claRecordId = clsRecordId;
            record.classId = classId;
            record.className = className;
            // record.scheduleId = scheduleId;
            let schoolId = $(value).find("input[name=schoolId]").val();
            record.schoolId = schoolId;
            let applyId = $(value).find("input[name=applyId]").val();
            record.applyId = applyId;
            let classStudentId = $(value).find("input[name=classStudentId]").val();
            record.classStudentId = classStudentId;
            let studentName = $(value).find("input[name=studentName]").val();
            record.studentName = studentName;
            let lessonConsume = $(value).find("input[name=lessonConsume]").val();
            record.lessonConsume = lessonConsume;
            let attendStatus = $(value).find("select").val();
            record.attendStatus = attendStatus;
            let leaveCount = parseInt($(value).find("input[name=leaveCount]").val());
            if (attendStatus == 1) {
                leaveCount++
            }
            record.leaveCount = leaveCount;
            records.push(record);
        })
        $.ajax({
            method: "post",
            contentType: "application/json",
            url: ctx + "teaching/record/addList",
            dataType: "json",
            async: false,
            data: JSON.stringify(records),
            success: function (result) {
                // changeStatus();
            }
        });

    }

    /* 改变排课记录状态 */
    // function changeStatus() {
    //     let scheduleStatus = $.common.trim($("input[name ='status']").val());
    //     $.ajax({
    //         type: "post",
    //         url: ctx + "teaching/schedule/edit",
    //         async: false,
    //         data: {
    //             "scheduleId": scheduleId,
    //             "status": scheduleStatus,
    //         }, success: function (result) {
    //         }
    //     });
    // }


    /**
     * 根据到课状态 选择 消耗课时
     * @param obj
     */
    function selectMe(obj) {
        var initConsume = $(obj).parent().prev().find("input[name='lessonConsume1']").val();
        var iptConsume = $(obj).parent().prev().find("input[name='lessonConsume']");
        if ($(obj).val() == 0) {
            iptConsume.val(initConsume);
        } else if ($(obj).val() == 1) {
            iptConsume.val(0);
        } else if ($(obj).val() == 2) {
            iptConsume.val(initConsume);
        }
        // console.log($(obj).val());
    }

    $("input[name='startDate']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true,
        initialDate: new Date()
    });

    $("input[name='startTime']").timepicker({
        minuteStep: 5,　　//分钟间隔
        showMeridian: false,　　//是否展示网咯时间
        // defaultTime: "",　　　　//默认时间
        secondStep: 1　　//秒钟间隔　　　　
    });
    $("input[name='endTime']").timepicker({
        minuteStep: 5,　　//分钟间隔
        showMeridian: false,　　//是否展示网咯时间
        // defaultTime: "",　　　　//默认时间
        secondStep: 1　　//秒钟间隔　　　　
    });

</script>
</body>
</html>

<script id="attendStatus" type="text/x-jquery-tmpl">
<div>
<select onChange="selectMe(this)"  name="attendStatus[${index}].type" class="form-control" th:with="type=${@dict.getType('sys_attend_status')}" style="width: 80px">
    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
</select>
</div>